/* eslint-disable array-callback-return,no-undef,prefer-destructuring */
import React, { Component } from 'react';
import { Modal, message } from 'antd';
import * as commonFunc from './commonFunc';
import * as commonBusiness from './commonBusiness'; /* 单据业务功能 */
import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';

const { confirm } = Modal;

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {
      };
      this.form = {};
      /*   表单对象   */
    }
    componentWillReceiveProps(nextProps) {
      const { formData, currentId } = nextProps;
      let { masterConfig } = nextProps;
      if (commonUtils.isEmptyArr(masterConfig) && formData.length > 0) {
        const sId = currentId !== undefined ? currentId : '';
        masterConfig = formData.filter(item => !item.bGrd)[0];
        const sysaccountperiodConfig = formData.filter(item => item.bGrd && item.sTbName === 'sysaccountperiod')[0];
        const sysaccountperiodColumn = commonFunc.getHeaderConfig(sysaccountperiodConfig);
        const sysbillnosettingsConfig = formData.filter(item => item.bGrd && item.sTbName === 'sysbillnosettings')[0];
        const sysbillnosettingsColumn = commonFunc.getHeaderConfig(sysbillnosettingsConfig);
        this.handleGetData(masterConfig, sysaccountperiodConfig, sysbillnosettingsConfig);
        this.props.onSaveState({
          masterConfig,
          sysaccountperiodConfig,
          sysaccountperiodColumn,
          sysbillnosettingsConfig,
          sysbillnosettingsColumn,
          sId,
          pageLoading: false,
        });
      }
    }

    shouldComponentUpdate(nextProps) {
      const { masterConfig, masterData } = nextProps;
      return commonUtils.isNotEmptyObject(masterConfig) && commonUtils.isNotEmptyObject(masterData);
    }
    handleGetData = (masterConfig, sysaccountperiodConfig, sysbillnosettingsConfig) => {
      const { currentId } = this.props;
      const sId = currentId !== undefined ? currentId : '';
      const condition = {
        sSqlCondition: {
          sParentId: masterConfig.sId,
        },
        bFilter: [{
          bFilterName: 'sPeriodId',
          bFilterValue: new Date().getFullYear().toString(),
          bFilterCondition: 'like',
        }],
      };
      this.handleGetMasterDataSet({
        configData: masterConfig, condition: { sId, pageSize: '', pageNum: '' },
      });
      this.props.handleGetDataSet({
        name: 'sysaccountperiod', configData: sysaccountperiodConfig, condition,
      });
      this.props.handleGetDataSet({
        name: 'sysbillnosettings', configData: sysbillnosettingsConfig, condition: { sId, pageSize: '', pageNum: '' },
      });
    };

    /* 获取后台数据（数据集） */
    handleGetMasterDataSet = async (params) => {
      const { token, sModelsId } = this.props;
      const {
        configData, condition,
      } = params;
      const configDataId = configData.sId;
      const dataUrl = `${commonConfig.server_host}syssystem/getSyssystemDataByFormcustomId/${configDataId}?sModelsId=${sModelsId}`;
      const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
      if (dataReturn.code === 1) {
        const masterData = {};
        const returnData = dataReturn.dataset.rows[0].dataSet;
        configData.gdsconfigformslave.forEach((itemConfig) => {
          returnData.filter(itemData => itemData.sName === itemConfig.sControlName.substring(1)).forEach((itemData) => {
            masterData[itemConfig.sControlName] = itemData.sValue;
            if (itemConfig.sControlName.substring(0, 1) === 'b') {
              if (itemData.sValue === '0') {
                masterData[itemConfig.sControlName] = false;
              } else if (itemData.sValue === '1') {
                masterData[itemConfig.sControlName] = true;
              }
            }
          });
        });
        this.props.onSaveState({
          masterData,
          syssystemsettingsData: returnData,
        });
      } else {
        this.props.getServiceError(dataReturn.msg);
      }
    };
    /*   取消操作  */
    handleCancel = () => {
      /*   待用数据声明   */
      const { masterConfig, sysaccountperiodConfig, sysbillnosettingsConfig } = this.props;
      const onGetDataOk = this.handleGetData;
      const onSaveStateOk = this.props.onSaveState;
      confirm({
        title: '确定要取消',
        onOk() {
          onGetDataOk(masterConfig, sysaccountperiodConfig, sysbillnosettingsConfig);
          onSaveStateOk({ enabled: false });
        },
        onCancel() {
        },
      });
    };
    /**   toolbar校验保存   */
    handleValidateSave = async () => {
      this.form.validateFieldsAndScroll((err) => {
        /*   验证通过与不通过走不同的流程   */
        if (err) { /*   验证失败   */
          /*   直接渲染显示错误提示   */
          for (const key of Object.keys(err)) {
            message.warning(err[key].errors[0].message);
          }
        } else { /*   验证成功   */
          const {
            masterConfig, masterData, sysaccountperiodConfig, sysaccountperiodData, sysbillnosettingsConfig, sysbillnosettingsData, syssystemsettingsData,
          } = this.props;
          const data = [];
          syssystemsettingsData.forEach((itemData) => {
            for (const key of Object.keys(masterData)) {
              if (itemData.sName === key.substring(1)) {
                itemData.sValue = masterData[key];
                itemData.handleType = 'update';
                if (key.substring(0, 1) === 'b') {
                  if (masterData[key] === true) {
                    itemData.sValue = '1';
                  } else if (masterData[key] === false) {
                    itemData.sValue = '0';
                  }
                } else if (key.substring(0, 1) === 's') {
                  if (commonUtils.isNotEmptyStr(masterData[key])) {
                    itemData.sValue = masterData[key].toString();
                  }
                } else if (key.substring(0, 1) === 'd' || key.substring(0, 1) === 'i') {
                  if (commonUtils.isNotEmptyNumber(masterData[key])) {
                    itemData.sValue = masterData[key].toString();
                  }
                }
              }
            }
          });
          data.push(commonBusiness.mergeData('syssystemsettings', masterConfig.sTbName, syssystemsettingsData));
          data.push(commonBusiness.mergeData('sysaccountperiod', sysaccountperiodConfig.sTbName, sysaccountperiodData));
          data.push(commonBusiness.mergeData('sysbillnosettings', sysbillnosettingsConfig.sTbName, sysbillnosettingsData));
          this.handleSaveData({ data, sClientType: '1' });
        }
      });
    };
    /**   toolbar保存   */
    handleSaveData = async (params) => {
      const {
        token, sModelsId, masterConfig, sysaccountperiodConfig, sysbillnosettingsConfig, masterData,
      } = this.props;
      const returnData = await commonBusiness.saveData({ token, value: params, sModelsId });
      if (commonUtils.isNotEmptyObject(returnData)) {
        this.props.onSaveState({
          enabled: false, currentId: masterData.sId,
        });
        this.handleGetData(masterConfig, sysaccountperiodConfig, sysbillnosettingsConfig);
        return true;
      } else {
        return false;
      }
    };
    /**   表单回带   */
    handleForm = (form) => {
      this.form = form;
    };
    /** 表格数据更改 */
    // name 不写完整的state名称作用为了要用到total // (name, changeValue, sId, dropDownData)
    handleTableChange = (name, sFieldName, changeValue, sId, dropDownData) => {
      /*   从CommonBase获取默认参数   */
      const {
        [`${name}Data`]: tableData, masterData, sModelsType, app,
      } = this.props;
      const iIndex = tableData.findIndex(item => item.sId === sId);
      const tableDataRow = this.props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
      const models = sModelsType.includes('sales/') || sModelsType.includes('manufacture/') ? 'Product' : 'Materials';
      tableData[iIndex] = commonBusiness.getCalculateAllMoney(app, models, sFieldName, masterData, tableDataRow);
      if (commonUtils.isEmptyStr(tableData[iIndex].handleType)) {
        tableData[iIndex].handleType = 'update';
      }
      this.props.onSaveState({ [`${name}Data`]: tableData, masterData });
    };
    /**   点击修改按钮操作   */
    handleEdit = () => {
      const { masterConfig, sysaccountperiodConfig, sysbillnosettingsConfig } = this.props;
      this.handleGetData(masterConfig, sysaccountperiodConfig, sysbillnosettingsConfig);
      this.props.onSaveState({ enabled: true });
    };
    render() {
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onEdit={this.handleEdit}
          onCancel={this.handleCancel}
          onSubmit={this.handleValidateSave}
          onReturnForm={this.handleForm}
          onDataChange={this.handleTableChange}
        />
      );
    }
  };
};
